//用状态机实现：字符串“abababx”的解析


function match(string){

    let state = start;
    for(let c of string){
        state = state(c);
    }
    return state === end;
}

// _ a   // _ ?
function start(c){
    if(c === "a")
        return foundA;
    else
        return start;
}

function end(c) {
    return end;
}
//a b    //a ?
function foundA(c) {
    if(c ==="b")
        return foundB;
    else
        return start(c);
}

//ab a     //ab ?
function foundB(c) {
    if(c ==="a"){
       return found2A
    }else
        return start(c);
}


// aba b    // aba ?
function found2A(c) {
    if(c ==="b")
        return found2B;
    else
        return foundA(c);
}

// abab a   // abab ?
function found2B(c) {
    if(c ==="a")
        return found3A;
    else
        return foundB(c);
}


// ababa b   // ababa ?
function found3A(c) {
    if(c ==="b")
        return found3B;
    else
        return found2A(c);
}


// ababab x   // ababab ?
function found3B(c) {
    if(c ==="x")
        return end;
    else
        return found2B(c);
}




console.log(match("abababababx"));
console.log(match("abxabxabababx"));
console.log(match("abxabxabababax"));
// console.log(match("abcabxa"));